import { ref, reactive, computed, onMounted } from "vue";
import { ElTag, ElButton } from "element-plus";
import { getConversionStats } from "@/api/ads";
import { message } from "@/utils/message";
import type {
  SearchFormProps,
  ConversionStatsItem,
  GroupOption,
  PlatformOption,
  PayChannelOption,
  ConversionStatsResponse,
  TabData
} from "./types";

// 获取平台文本
const getPlatformText = (platform: number | string | null | undefined): string => {
  if (!platform) return "未知平台";

  const platformNum = typeof platform === 'string' ? parseInt(platform) : platform;

  switch (platformNum) {
    case 1:
      return "TikTok";
    case 2:
      return "Facebook";
    default:
      return "未知平台";
  }
};

export function useAdConversion() {
  const loading = ref(false);
  const dataList = ref<ConversionStatsItem[]>([]);
  const groupOptions = ref<GroupOption[]>([]);
  const platformOptions = ref<PlatformOption[]>([]);
  const payChannelOptions = ref<PayChannelOption[]>([]);
  const activeTab = ref<string>('all'); // 当前激活的tab
  const allTabsData = ref<Record<string, TabData>>({}); // 存储所有Tab的数据

  // 排序状态
  const sortField = ref<string>('order_count'); // 默认按订单数排序
  const sortOrder = ref<'asc' | 'desc'>('desc'); // 默认倒序

  // 获取最近7天的日期范围
  const getLastSevenDays = (): [string, string] => {
    const today = new Date();
    const lastWeek = new Date(today);
    lastWeek.setDate(today.getDate() - 6); // 最近7天：今天往前推6天

    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    return [formatDate(lastWeek), formatDate(today)];
  };

  // 获取当前月份的开始和结束日期
  const getCurrentMonthRange = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth(); // 0-11

    const startDate = new Date(year, month, 2);
    const endDate = new Date(year, month + 1, 1); // 下个月的第1天，即当前月的最后一天

    const formatDate = (date: Date) => {
      return date.toISOString().split('T')[0];
    };

    return {
      start: formatDate(startDate),
      end: formatDate(endDate)
    };
  };

  const currentMonthRange = getCurrentMonthRange();

  // 快速选择字段
  const quickSelect = ref('7day');

  // 搜索表单
  const form = reactive<SearchFormProps>({
    group_id: null,
    platform: null,
    date_range: getLastSevenDays(), // 默认选择最近7天
    pay_channel: null
  });

  // 格式化金额
  const formatAmount = (amount: number): string => {
    return new Intl.NumberFormat('en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }).format(amount);
  };

  // 获取转化率类型（用于颜色分级）- 调整为小数阈值
  const getConversionRateType = (rate: number): "success" | "info" | "warning" | "danger" => {
    if (rate >= 1.0) return "success"; // 绿色 (≥100%)
    if (rate >= 0.5) return "info"; // 蓝色 (≥50%)
    if (rate >= 0.2) return "warning"; // 橙色 (≥20%)
    return "danger"; // 红色 (<20%)
  };

  // 排序函数
  const sortData = (data: ConversionStatsItem[]): ConversionStatsItem[] => {
    if (!sortField.value) return data;

    const sortedData = [...data].sort((a, b) => {
      const aValue = a[sortField.value as keyof ConversionStatsItem] as number;
      const bValue = b[sortField.value as keyof ConversionStatsItem] as number;

      if (sortOrder.value === 'asc') {
        return aValue - bValue;
      } else {
        return bValue - aValue;
      }
    });

    return sortedData;
  };

  // 处理排序变化
  const handleSortChange = (field: string) => {
    if (sortField.value === field) {
      // 如果点击的是当前排序字段，切换排序顺序
      sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
    } else {
      // 如果是新字段，设置为倒序
      sortField.value = field;
      sortOrder.value = 'desc';
    }

    // 重新排序当前数据
    if (allTabsData.value[activeTab.value]) {
      dataList.value = sortData([...allTabsData.value[activeTab.value].data]);
    }
  };

  // 表格列配置
  const columns = ref([
    {
      label: "类型",
      prop: "type",
      width: 80,
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => (
        <span class={`font-medium ${row.type === 'group' ? 'text-blue-600' : 'text-green-600'}`}>
          {row.type === 'group' ? '投放组' : '投放人员'}
        </span>
      )
    },
    {
      label: "名称",
      prop: "name",
      minWidth: 120,
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => (
        <div>
          <div class="font-medium">{row.name}</div>
          {/* {row.parent_name && (
            <div class="text-xs text-gray-500">
              所属：{row.parent_name}
            </div>
          )} */}
        </div>
      )
    },
    {
      label: "ORDER",
      prop: "order_count",
      minWidth: 100,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => (
        <span class="font-mono">{row.order_count.toLocaleString()}</span>
      )
    },
    {
      label: "SA",
      prop: "total_sales",
      minWidth: 120,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => (
        <span class="font-mono text-green-600">
          {formatAmount(row.total_sales)}
        </span>
      )
    },
    {
      label: "AD",
      prop: "total_cost",
      minWidth: 120,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => (
        <span class="font-mono text-red-500">
          {formatAmount(row.total_cost)}
        </span>
      )
    },
    {
      label: "RO",
      prop: "conversion_rate",
      minWidth: 100,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => {
        // 当广告费用为0时，显示"-"
        if (row.total_cost === 0) {
          return (
            <ElTag
              type="info"
              effect="light"
              size="small"
            >
              -
            </ElTag>
          );
        }

        return (
          <ElTag
            type={getConversionRateType(row.conversion_rate)}
            effect="light"
            size="small"
          >
            {row.conversion_rate.toFixed(2)}
          </ElTag>
        );
      }
    },
    {
      label: "PER AD",
      prop: "cost_per_order",
      minWidth: 130,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => {
        // 当订单数为0时，显示"-"
        if (row.order_count === 0) {
          return <span class="font-mono text-gray-500">-</span>;
        }

        return (
          <span class="font-mono">
            {formatAmount(row.cost_per_order)}
          </span>
        );
      }
    },
    {
      label: "PER S",
      prop: "avg_order_value",
      minWidth: 100,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => {
        // 当订单数为0时，显示"-"
        if (row.order_count === 0) {
          return <span class="font-mono text-gray-500">-</span>;
        }

        return (
          <span class="font-mono">
            {formatAmount(row.avg_order_value)}
          </span>
        );
      }
    },
    {
      label: "弃单",
      prop: "abandoned_orders",
      minWidth: 110,
      sortable: "custom",
      cellRenderer: ({ row }: { row: ConversionStatsItem }) => (
        <span class="font-mono text-gray-500">
          {row.abandoned_orders.toLocaleString()}
        </span>
      )
    },
    {
      label: "操作",
      prop: "action",
      minWidth: 80,
      fixed: "right",
      cellRenderer: (data) => {
        const row = data.row as ConversionStatsItem;
        // 只有投放人员且有订单时才显示查看按钮
        if (row.type === 'user' && (
          (row.orders_dcl_list && row.orders_dcl_list.length > 0) ||
          (row.orders_qd_list && row.orders_qd_list.length > 0)
        )) {
          return (
            <ElButton
              type="primary"
              link
              size="small"
              onClick={() => viewOrderDetails(row)}
            >
              查看
            </ElButton>
          );
        }
        return "";
      }
    }
  ]);

  // 获取数据
  const fetchData = async () => {
    try {
      loading.value = true;

      // 处理日期范围 - 直接传递date_range数组，不再传递pay_channel参数
      const requestData = {
        group_id: form.group_id,
        platform: form.platform,
        // 确保date_range有默认值
        date_range: form.date_range || [currentMonthRange.start, currentMonthRange.end]
      };

      const response = await getConversionStats(requestData);

      if (response.success) {
        const data = response.data as ConversionStatsResponse;

        // 存储所有Tab数据
        allTabsData.value = data.tabs_data;

        // 设置当前Tab的数据并应用排序
        if (allTabsData.value[activeTab.value]) {
          dataList.value = sortData(allTabsData.value[activeTab.value].data);
        }

        // 只在首次加载时更新选项
        if (groupOptions.value.length === 0) {
          groupOptions.value = data.group_options || [];
        }
        if (platformOptions.value.length === 0) {
          platformOptions.value = data.platform_options || [];
        }
        if (payChannelOptions.value.length === 0) {
          payChannelOptions.value = data.pay_channel_options || [];
        }
      } else {
        message(response.message || "获取数据失败", { type: "error" });
      }
    } catch (error) {
      console.error("获取转化率统计数据失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  };

  // 切换Tab
  const handleTabChange = (tabName: string) => {
    activeTab.value = tabName;
    // 从本地缓存的数据中切换，无需重新请求
    if (allTabsData.value[tabName]) {
      // 确保触发响应式更新并应用排序
      dataList.value = sortData([...allTabsData.value[tabName].data]);
    }
  };

  /** 时间快速选择 */
  const selectTimeRange = (value: string) => {
    const today = new Date();
    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    switch (value) {
      case 'today': {
        form.date_range = [formatDate(today), formatDate(today)];
        break;
      }
      case 'yesterday': {
        const yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);
        form.date_range = [formatDate(yesterday), formatDate(yesterday)];
        break;
      }
      case '7day': {
        const lastWeek = new Date(today);
        lastWeek.setDate(today.getDate() - 6);
        form.date_range = [formatDate(lastWeek), formatDate(today)];
        break;
      }
      case '30day': {
        const lastMonth = new Date(today);
        lastMonth.setDate(today.getDate() - 29);
        form.date_range = [formatDate(lastMonth), formatDate(today)];
        break;
      }
      case 'month': {
        const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
        const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        form.date_range = [formatDate(firstDayOfMonth), formatDate(lastDayOfMonth)];
        break;
      }
      case 'lastmonth': {
        const firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
        const lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
        form.date_range = [formatDate(firstDayOfLastMonth), formatDate(lastDayOfLastMonth)];
        break;
      }
      case 'diy':
      default: {
        // 自定义，不做处理
        return;
      }
    }

    // 除了自定义选择，其他都自动查询
    fetchData();
  };

  /** 日期变化处理 */
  const handleDateChange = () => {
    quickSelect.value = 'diy';
  };

  // 搜索
  const onSearch = () => {
    fetchData();
  };

  // 重置表单
  const resetForm = (formEl: any) => {
    if (formEl) {
      formEl.resetFields();
    }
    Object.assign(form, {
      group_id: null,
      platform: null,
      date_range: getLastSevenDays(), // 重置到最近7天
      pay_channel: null
    });
    quickSelect.value = '7day'; // 重置快速选择
    activeTab.value = 'all'; // 重置到全部tab
    onSearch();
  };

  // 弹窗状态管理
  const orderDialogVisible = ref(false);
  const currentOrderData = ref<{
    name: string;
    orders_dcl_list: string[];
    orders_qd_list: string[];
  }>({
    name: '',
    orders_dcl_list: [],
    orders_qd_list: []
  });

  // 订单弹窗Tab控制
  const activeOrderTab = ref('dcl');

  // 查看订单详情
  const viewOrderDetails = (row: ConversionStatsItem) => {
    currentOrderData.value = {
      name: row.name,
      orders_dcl_list: row.orders_dcl_list || [],
      orders_qd_list: row.orders_qd_list || []
    };

    // 设置默认显示的Tab（优先显示有数据的Tab）
    if (currentOrderData.value.orders_dcl_list.length > 0) {
      activeOrderTab.value = 'dcl';
    } else if (currentOrderData.value.orders_qd_list.length > 0) {
      activeOrderTab.value = 'qd';
    } else {
      activeOrderTab.value = 'dcl';
    }

    orderDialogVisible.value = true;
  };

  // 关闭订单详情弹窗
  const closeOrderDialog = () => {
    orderDialogVisible.value = false;
  };

  // 初始化
  onMounted(() => {
    fetchData();
  });

  return {
    loading,
    dataList,
    form,
    columns,
    groupOptions,
    platformOptions,
    payChannelOptions,
    activeTab,
    allTabsData,
    quickSelect,
    sortField,
    sortOrder,
    onSearch,
    resetForm,
    handleTabChange,
    handleSortChange,
    selectTimeRange,
    handleDateChange,
    formatAmount,
    getConversionRateType,
    getPlatformText,
    orderDialogVisible,
    currentOrderData,
    viewOrderDetails,
    closeOrderDialog,
    activeOrderTab
  };
}
